import { getCache, setCache, removeCache } from '@/utils/session';
import { login, logout } from '@/api/user';
import { asyncRoutes } from '@/router/modules';
import { deepClone } from '@/utils';
import mainLayout from '@/layouts/mainLayout';
import { baseRoute,resetRouter } from '@/router';
import tenantApi from '@/api/system/tenant'
import userApi from '@/api/system/user'

//按钮权限
let permissions = []
//第一个菜单信息
let firstMenu = {}
//处理路由信息
let {getRouters} = dealRemoteRouters();

const state = {
    accountInfo: '',
    tenantInfo:getCache('tenantInfo') || '',
    isRoutersTag: false,
    token: getCache('TOKEN') || '',
    tenantList:[],
    tenant: '',
    routes: baseRoute.concat(getRouters),
    homeRoute: getCache('homeRoute') || '',
    permissions:getCache('permissions') || []
};

const mutations = {
    SET_TOKEN(state, token) {
        state.token = token;
    },
    SET_TENANT(state,tenant){
        state.tenant = tenant;
    },
    SET_TENANTLIST(state,tenantList){
        state.tenantList = tenantList;
    },
    SET_USERINFO(state, userInfo) {
        state.accountInfo = userInfo;
    },
    SET_TENANTINFO(state,tenantInfo){
        state.tenantInfo = tenantInfo;
    },
    SET_STAGEACCOUNT(state, userInfo) {
        state.stageAccount = userInfo;
    },
    SET_ROUTE(state, route) {
        state.routes = baseRoute.concat(route);
        state.homeRoute = firstMenu?.path;
    },
    SET_PERMISSIONS(state,permissions){
        state.permissions = permissions
    }
};

const actions = {
    login({ commit }, userInfo) {
        return new Promise((resolve, reject) => {
            let type = getCache('tenant') || 'master';
            login(type ,userInfo)
                .then(async res => {
                    let {code,data} = res;
                    if(code==200){
                        commit('SET_TOKEN', data.token);
                        setCache('TOKEN', data.token);
                        let {companyCode,userId} = data.user;
                        let tenantResult = await tenantApi.remoteList({companyCode,page:1,size:1});
                        let userResult = await userApi.remoteList({userId,page:1,size:1});
                        let userInfo = userResult.data.list[0] || {};
                        let tenantInfo = tenantResult.data.list[0] || {};
                        let {getRouters,permissions} = dealRemoteRouters(data.permissions);
                        
                        setCache('userInfo',userInfo)
                        setCache('tenantInfo',tenantInfo)
                        setCache('permissions',permissions)
                        commit('SET_PERMISSIONS',permissions);
                        commit('SET_ROUTE', getRouters);
                        commit('tagsView/ADD_TAGS', firstMenu, { root: true })

                        resolve({res,routers:getRouters,userInfo:userInfo});
                    }else{
                        reject(res);
                    }
                })
                .catch(err => {
                    console.log(err)
                    reject(err);
                });
        });
    },
    async getUserInfo({dispatch, commit, state }){
        let userInfo = getCache('userInfo')||'';
        let {userType,tenantCode} = userInfo;
        if(userType=='super_admin'){
            await dispatch('remoteTenantList')
        }else{
            commit('SET_TENANT',tenantCode)
        }
        commit('SET_USERINFO', userInfo);
        commit('tagsView/ADD_TAGS', firstMenu, { root: true })
        return userInfo;
    },
    //isApi:是否需要调用退出接口
    logout({ commit}, isApi=true ) {
        return new Promise(async (resolve, reject) => {
            let res = null
            try{
                if(isApi){
                    res = await logout();
                }
                commit('SET_TOKEN', '');
                commit('SET_USERINFO', '');
                commit('SET_STAGEACCOUNT', null);
                commit('SET_ROUTE', '');
                removeCache('TOKEN');
                removeCache('userInfo');
                removeCache('permissions');
                removeCache('routers');
                resetRouter();
                resolve();
            }catch(err){
                reject(err);
            }finally{

            }
        });
    },
    async remoteTenantList({commit}){
        let res = await tenantApi.remoteList({page:1,size:1000});
        let {list} = res.data;
        let firstItem = list[0] || {companyCode:''};
        commit('SET_TENANT',firstItem.companyCode)
        commit('SET_TENANTLIST',list)
    },
    removeRouter({commit}){
        return new Promise((resolve, reject) => {
            commit('SET_ROUTE', []);
            resolve([]);
        });
    },
    updateInfo({ commit }, userInfo) {
        return new Promise((resolve, reject) => {
            commit('SET_USERINFO', userInfo);
            resolve();
        });
    }
};

//处理需要的路由形式
export function dealRemoteRouters(permission){
    let permissionBox = [];
    if(permission && permission.length){
        permission.map(item=>{
            permissionBox.push(JSON.parse(item))
        })
        setCache('routers',permissionBox)
    }else{
        permissionBox = getCache('routers') || []
    }
    permissions = [];
    let result = dealPermissions(permissionBox);
    firstMenu = getFirstMenu(result[0]);
    setCache('homeRoute',firstMenu.path)
    let getRouters = asyncRoutes(result,firstMenu.path);
    return {getRouters,permissions};
}

//处理用户菜单中权限信息
export function dealPermissions(permissionBox){
    if(!permissionBox || !permissionBox.length) return [];
    permissionBox.map(item=>{
        item.name = item.menuName;
        item.meta = { title:item.menuName, icon: item.icon };
        if(item.menuType=='M'){
            item.component = mainLayout;
            let res = getFirstMenu(item)
            item.redirect = res.path || '/'
        }
        if(item.children && item.children.length){
            item.children = dealPermissions(item.children);
        }else{
            item.children = null;
        }
        if(item.menuType=='F'){
            permissions.push(item.path)
        }
        if(item.menuType=='C'){
            item.children = null
            item.component = () => import('@/views'+item.path)
        }
    });
    return permissionBox;
}

//权限菜单中第一个实质性的菜单
export function getFirstMenu(item){
    if(!item) return {};
    if(item.menuType =='C'){
        return item;
    }
    if(item.menuType=='M'){
        return getFirstMenu(item.children[0])
    }
}


export default {
    namespaced: true,
    state,
    mutations,
    actions
};
